package com.zhongjian.technologycal.mall.activity.personal.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.adapter.AddressListAdaper;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.base.BaseContacts;
import com.zhongjian.technologycal.mall.bean.AddressBean;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.drakeet.materialdialog.MaterialDialog;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/12/13.
 * 添加新地址页面的实现
 */

public class NewsAddressListManageActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.address_recylerview)
    ListView address_recylerview;
    private List<AddressBean> listItems = new ArrayList<>();
    private AddressListAdaper addressListAdaper;
    private int RESULTCODE = 1002;
    private MaterialDialog materialDialog = null;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    addressListAdaper.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected void beforeInit() {
        super.beforeInit();
        super.beforeInit();
//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_main_title.setText("收货地址");
        addressListAdaper = new AddressListAdaper(getBaseContext(), listItems);
        address_recylerview.setAdapter(addressListAdaper);
        address_recylerview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {


            }
        });
        address_recylerview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, long l) {
                materialDialog = new MaterialDialog(NewsAddressListManageActivity.this)
                        .setMessage("确定删除这个地址吗？")
                        .setPositiveButton("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                initViewDeleteAddress(listItems.get(position).getData().get(position).getId());
                                materialDialog.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                materialDialog.dismiss();
                            }
                        });
                materialDialog.setCanceledOnTouchOutside(true);
                materialDialog.show();
                return true;
            }
        });

    }

    @Override
    public void initPresenter() {
        initRequestAddressList();
    }

    /**
     *
     */
    private void initRequestAddressList() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext())
                .getRequest(BaseContacts.URL_ADDRESS_MANAGE + UserUtils.getUserToken(),
                        new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                            }

                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                try {
                                    Gson gson = new Gson();
                                    AddressBean addressBean = gson.fromJson(responseBody.string(), AddressBean.class);
                                    if (addressBean.getError_code() == 0) {
                                        List<AddressBean> forList = new ArrayList<>();
                                        for (int i = 0; i < addressBean.getData().size(); i++) {
                                            forList.add(addressBean);
                                        }
                                        setData(forList);
                                    } else if (addressBean.getError_code() == 3) {
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        sendBroadcast(intent);
                                    } else {
                                        ToastUitl.showShort(addressBean.getError_message());
                                    }


                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            }
                        });


    }

    private void setData(List<AddressBean> foreshowList) {
        if (listItems.size() > 0) {
            listItems.clear();
        }
        for (AddressBean vo : foreshowList) {
            listItems.add(vo);
        }
        handler.sendEmptyMessage(0);

    }


    @Override
    protected void onResume() {
        super.onResume();
        initRequestAddressList();
    }


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_address_list;
    }

    @OnClick(R.id.iv_back_page)
    public void onClickFinish() {
        finish();
    }

    /**
     * 新增收货地址
     */
    @OnClick(R.id.ll_add_new_address)
    public void onClickAddNewAddress() {
        Intent intent = new Intent();
        intent.setClass(getBaseContext(), AddNewsAddressActivity.class);
        startActivity(intent);
    }

    /**
     * 删除收货地址
     *
     * @param id
     */
    private void initViewDeleteAddress(int id) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }

        Map<String, Object> maps = new HashMap<>();
        maps.put("token", UserUtils.getUserToken());
        maps.put("id", id);
        RequestBody body = RequestBody.create(
                okhttp3.MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(maps));
        HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequestDeleteAddressById(body, new Subscriber<ResponseBody>() {
            @Override
            public void onStart() {
                super.onStart();
                LoadingDialog.showDialogForLoading(NewsAddressListManageActivity.this);
            }

            @Override
            public void onCompleted() {
                LoadingDialog.cancelDialogForLoading();
            }

            @Override
            public void onError(Throwable e) {
                LoadingDialog.cancelDialogForLoading();
            }

            @Override
            public void onNext(ResponseBody responseBody) {
                LoadingDialog.cancelDialogForLoading();
                try {
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                    if (baseBean.getError_code() == 0) {
                        initRequestAddressList();
                        ToastUitl.showShort(baseBean.getError_message());
                    } else if (baseBean.getError_code() == 3) {
                        Intent intent = new Intent();
                        intent.setAction("com.broadcast.info_out_line");
                        sendBroadcast(intent);
                    } else {
                        ToastUitl.showShort(baseBean.getError_message());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
